import { message } from 'antd';
import { AUTH_STORE } from '@/constants';
import { HttpStatusCode } from '@/constants/api';
import { resetAuthStore } from '@/store/authStore';
import { resetUserStore } from '@/store/userStore';
import axios, { Axios, AxiosRequestConfig, AxiosResponse } from 'axios';
import { isValidTokenTime } from '@/utils/auth';
import { local } from '@/utils/storage';


export class Request {
  private instance: Axios;

  constructor(props: AxiosRequestConfig, useInterceptors = true) {
    // 使用拦截器
    this.instance = axios.create(props);
    if (useInterceptors) {
      this.initInterceptors();
    }
  }

  initInterceptors() {
    this.instance.interceptors.request.use(
      this.useRequestOnFulfilled(),
      this.useRequestOnReject()
    );
    this.instance.interceptors.response.use(
      this.useResponseOnFulfilled(),
      this.useResponseOnReject()
    );
  }

  request<T = any, R = AxiosResponse<T>, D = any>(
    props: AxiosRequestConfig<D>
  ): Promise<R> {
    return this.instance.request(props);
  }

  useRequestOnFulfilled() {
    return (config: AxiosRequestConfig): AxiosRequestConfig => {
      // 拦截请求配置，进行个性化处理。
      // 添加 authorization头 Bearer token
      let headers = config.headers || {};
      if (headers['authorization']) {
        return config;
      }
      const { token } = local.get<AuthStructure>(AUTH_STORE, {
        token: '',
        expire: '',
      } as AuthStructure);
      headers['authorization'] = 'Bearer ' + token;
      return { ...config, headers };
    };
  }

  useResponseOnFulfilled() {
    return (response: AxiosResponse): Promise<any> => {
      const { data } = response;
      if (data?.code) {
        const { code, message: msg } = data;

        if (String(code).startsWith('2') && String(code).length == 3) {
          return Promise.resolve(response);
        }

        switch (code) {
          case HttpStatusCode.StatusErrVerifyCode ||
            HttpStatusCode.StatusExpireVerifyCode ||
            HttpStatusCode.StatusSendSmsFail:
            message.error(msg);
            break;
          case HttpStatusCode.StatusUnauthorized:
            const { token, expire } = local.get<AuthStructure>(AUTH_STORE);
            if (token && expire && !isValidTokenTime(expire)) {
              message.error('登录过期，请重新登录！');
              local.set(AUTH_STORE, { token: '', expire: '' } as AuthStructure);
              resetAuthStore();
              resetUserStore();
            }
            message.error('请先登录');
            break;
          case HttpStatusCode.StatusForbidden:
            message.error('没有权限访问，请联系管理员');
            break;
          case HttpStatusCode.StatusUnprocessableEntity:
            message.error('参数错误');
            break;
          case HttpStatusCode.StatusInternalServerError ||
            HttpStatusCode.StatusBadRequest:
            message.error(msg);
            break;
          default:
            message.error(msg);
        }
        return Promise.reject(response);
      }
      return Promise.resolve(response);
    };
  }

  useRequestOnReject() {
    return (error: any): Promise<any> => {
      return Promise.reject(error);
    };
  }

  useResponseOnReject() {
    return (error: any): Promise<any> => {
      return Promise.reject(error);
    };
  }
}

export const commonHttp = new Request({
  baseURL: import.meta.env.VITE_BASEURL,
  timeout: 3000,
});
